import { formatGMTDate, toPercent, arrayToObject } from '../../../../assets/js/util.js'
import echarts from 'echarts'
export default {
    data() {
        return {
            title: '活动分析',
            xlsxTitle: '',
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            loading: false,
            searchable: false,
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            activeName: '1',
            dialogFormVisible: false,
            tableWidth: '100%',
            contentWidth: '100%',
            date: '',
            //默认的表单参数
            form: {
                dateType: 7,
                dstart: '', //开始时间
                dend: '', //结束时间
                server: '0', //区服id
                platform: '0',
                channel: '0',
                userType: '-99999',
                activityType: '1',
                activities: [],
                activityType2: '1',
                activities2: [],
                platformItmes: [],
                channelItems: [],
                serverItmes: [],
                userTypes: [],
                rolelevelMap: [],
                activityTypes: [],
                activityItems: [],
                selectedActivities: [],
                selectedActivities2: []
            },
            inputWidth: '220px',
            formLabelWidth: '100px',
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            activityAnalysisTableHead: [
                { prop: "day", label: "日期" },
                { prop: "activityTypeStr", label: "活动类型" },
                { prop: "activityName", label: "活动名称" },
                { prop: "userNum", label: "参与人数" },
                { prop: "joinNum", label: "参与次数" },
                { prop: "joinProUserNum", label: "人均参与次数" },
                { prop: "okUserNum", label: "满足条件人数" },
                { prop: "userJoinRate", label: "参与率" }
            ],
            activityAnalysisTableData: [],
            activityAnalysisTableDataAll: [],
            /**charts 活动参与率 任务/副本 折线*/
            lineChartSetting: {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data: []
                },
                grid: {
                    left: '0%',
                    right: '1%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: '1',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'circle',
                }, {
                    name: '2',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'roundRect',
                }, {
                    name: '3',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'triangle',
                }]
            },
            /**charts 人均参与次数 任务/副本 柱状*/
            barChartsSetting: {
                legend: {
                    data: ['安卓', 'iOS']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    data: ['付费人数比例', '付费金额比例', '付费人数比例', '付费金额比例', '付费人数比例', '付费金额比例'],
                    axisLabel: {
                        interval: 0,
                        rotate: -90, //倾斜度 -90 至 90 默认为0
                        margin: 10,
                    }
                }],
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLabel: {
                        formatter: function(value) {
                            return toPercent(value);
                        }
                    }
                }],
                tooltip: [{
                    trigger: 'axis',
                    formatter: function(a) {
                        var temp = '';
                        for (var i = 0, len = a.length; i < len; i++) {
                            temp = temp + a[i].seriesName + ':' + toPercent(a[i].value) + '</br>';
                        }
                        return a[0].name + '</br>' + temp;

                    }
                }],
                series: [{
                        name: '安卓',
                        type: 'bar',
                        data: ['46.52', '39.4', '46.52', '39.4', '46.52', '39.4'],
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function(value) {
                                    return toPercent(value.value);
                                }
                            }

                        }
                    },
                    {
                        name: 'iOS',
                        type: 'bar',
                        data: ['4.82', '10.6', '4.82', '10.6', '4.82', '10.6'],
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function(value) {
                                    return toPercent(value.value);
                                }
                            }

                        }
                    }
                ]
            }
        }
    },
    computed: {
        // xlsx() {
        //     return this.title + '.xlsx'
        // }
    },
    methods: {
        //默认成功处理函数
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        //默认错误处理函数
        errorFun(data) {
            this.$message.error(data);
        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        //时间变化
        dateChange(val) {
            var t = val.split(' - ')
            this.form.dstart = t[0];
            this.form.dend = t[1];
        },
        //重置表单
        reset(form) {
            this.$refs[form].resetFields();
        },
        //提交表单
        search() {
            var that = this;
            that.loads(); //加载 查询按钮不可用
            var formParam = {
                dstart: that.form.dstart,
                dend: that.form.dend,
                platform: that.form.platform,
                channel: that.form.channel,
                server: that.form.server,
                userType: that.form.userType,
                activities: that.form.activities,
                activities2: that.form.activities2,
                activityType: that.form.activityType,
                activityType2: that.form.activityType2
            };
            var stringParam = that.makeParam(formParam);
            stringParam = encodeURI(stringParam);
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "search",
                    ps: stringParam
                }
            }).then(function(res) {
                that.loads();
                var data = JSON.parse(res.body)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["res"]) === 0) {
                    that.activityAnalysisTableDataAll = data.activityDatas;
                    that.formatData();
                    that.dataTotal = that.activityAnalysisTableDataAll.length;
                    that.activityAnalysisTableData = that.activityAnalysisTableDataAll.slice((that.currentPage - 1) * that.pageSize, that.currentPage * that.pageSize);
                    that.setLineCharts(data, 'joinRateTaskCharts');
                    that.setBarCharts(data, 'joinRateAvgTaskCharts');
                } else {
                    that.loads();
                    that.errorFun(data.msg)
                }
            });
        },
        makeParam(jsonParam) {
            var stringParam = "";
            var i = 0;
            for (var key in jsonParam) {
                if (i == 0) {
                    stringParam = stringParam + key + "=" + jsonParam[key];
                } else {
                    if (key === 'activities' || key === 'activities2') {
                        stringParam = stringParam + "&" + key + "=" + JSON.stringify(jsonParam[key]);
                    } else {
                        stringParam = stringParam + "&" + key + "=" + jsonParam[key];
                    }
                }
                i++;
            }
            return stringParam;
        },
        // 表格下载
        excel(a, b, sheet) {

            this.xlsxTitle = sheet + "-" + this.form.dstart + "到" + this.form.dend;
            this.downloadExl(this.activityAnalysisTableHead, this.activityAnalysisTableDataAll, this.xlsxTitle, this.title);

        },
        /*分页器*/
        handleSizeChange(val) {
            this.pageSize = val;
            this.activityAnalysisTableData = this.activityAnalysisTableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.activityAnalysisTableData = this.activityAnalysisTableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        setLineCharts(d, chartObj) {
            if (d.activityChart === undefined) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
                if (d.chart === undefined) {
                    var data = {
                        "columnkeys": [],
                        "names": [],
                        "data": [
                            []
                        ]
                    }
                } else {
                    var data = d['chart']['jsonStr'];
                }
            } else {
                var data = d['activityChart']['jsonStr'];
            }
            this[chartObj].setOption({
                legend: {
                    data: data["names"] //
                },
                xAxis: [{
                    data: data["columnkeys"] //
                }],
                series: this.formatLineChartSeries(data["names"], data["data"])
            });
        },
        formatLineChartSeries(names, data) {
            var seriesArr = [];
            for (var index in names) {
                seriesArr.push({ name: names[index], data: data[index], type: "line" });
            }
            return seriesArr;
        },
        setBarCharts(d, chartObj) {
            if (d.activityChart === undefined) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
                if (d.chart === undefined) {
                    var data = {
                        "columnkeys": [],
                        "names": [],
                        "data": [
                            []
                        ]
                    }
                } else {
                    var data = d['chart']['jsonStr'];
                }
            } else {
                var data = d['activityChart2']['jsonStr'];
            }
            this[chartObj].setOption({
                legend: {
                    data: data["names"]
                },
                xAxis: [{
                    data: data["columnkeys"]
                }],
                series: this.formatBarChartSeries(data["names"], data["data"])
            });

        },
        formatBarChartSeries(names, data) {
            var seriesArr = [];
            for (var index in names) {
                seriesArr.push({ name: names[index], data: data[index], type: "bar" });
            }
            return seriesArr;
        },
        selectActivityType(val) {
            this.form.activities = val;
            var chartObj = '';
            if (this.form.activityType === "1") {
                chartObj = 'joinRateTaskCharts';
            } else if (this.form.activityType === "2") {
                chartObj = 'joinRateSubTaskCharts';
            }
            this.search();
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "handleActivityChange",
                    ps: `activities=${val}`
                }
            }).then(function(res) {
                var data = JSON.parse(res.body)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["res"]) === 0) {
                    this.activityAnalysisTableDataAll = [];
                    this.activityAnalysisTableDataAll = data.activityDatas;
                    this.formatData();
                    this.dataTotal = this.activityAnalysisTableDataAll.length;
                    this.activityAnalysisTableData = this.activityAnalysisTableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                    this.setLineCharts(data, chartObj);
                } else {
                    // this.errorFun(data['msg']);
                }
            });
        },
        selectActivityType2(val) {
            this.form.activities = val;
            var chartObj = '';
            if (this.form.activityType === "1") {
                chartObj = 'joinRateAvgTaskCharts';
            } else if (this.form.activityType === "2") {
                chartObj = 'joinRateAvgSubTaskCharts';
            }
            this.search();
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "handleActivityChange2",
                    ps: `activities=${val}`
                }
            }).then(function(res) {
                var data = JSON.parse(res.body)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["res"]) === 0) {
                    this.setLineCharts(data, chartObj);
                } else {
                    // this.errorFun(data.msg);
                }
            });
        },
        changeActive(val) {
            this.form.activityType = val.name;
            var chartObj = '';
            if (val.name === "1") {
                chartObj = 'joinRateTaskCharts';
            } else if (val.name === "2") {
                chartObj = 'joinRateSubTaskCharts';
            }
            // this.$http.jsonp(`${this.SRC}data/get.do`, {
            //     params: {
            //         p: this.DP.p,
            //         f: this.DP.f,
            //         a: "updateActivityType",
            //         ps: `activityType=${val.name}`
            //     }
            // }).then(function(res) {
            //     var data = JSON.parse(res.body)
            //     data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
            //     if (parseInt(data["res"]) === 0) {
            //         this.activityAnalysisTableDataAll = [];
            //         this.activityAnalysisTableDataAll = data.activityDatas;
            //         this.formatData();
            //         this.dataTotal = this.activityAnalysisTableDataAll.length;
            //         this.activityAnalysisTableData = this.activityAnalysisTableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            //         this.setLineCharts(data, chartObj);
            //     } else {
            //        // this.errorFun(data.msg);
            //     }
            // });
        },
        changeActive2(val) {
            this.form.activityType2 = val.name;
            var chartObj = '';
            if (val.name === "1") {
                chartObj = 'joinRateAvgTaskCharts';
            } else if (val.name === "2") {
                chartObj = 'joinRateAvgSubTaskCharts';
            }
            // this.$http.jsonp(`${this.SRC}data/get.do`, {
            //     params: {
            //         p: this.DP.p,
            //         f: this.DP.f,
            //         a: "updateActivityType2",
            //         ps: `activityType=${val.name}`
            //     }
            // }).then(function(res) {
            //     var data = JSON.parse(res.body)
            //     data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
            //     if (parseInt(data["res"]) === 0) {
            //         this.setBarCharts(data, chartObj);
            //     } else {
            //        // this.errorFun(data.msg);
            //     }
            // });
        },
        /*获取初始数据*/
        getData: function() {
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "initParam",
                    ps: ""
                }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data.res) == 0) {
                    this._dataPush(data.platformItmes, this.form.platformItmes);
                    this._dataPush(data.channelItmes, this.form.channelItems);
                    this._dataPush(data.serverItmes, this.form.serverItmes);
                    this._dataPush(data.userTypes, this.form.userTypes);
                    this._dataPush(data.activityTypes, this.form.activityTypes);
                    this._dataPush(data.activityItmes, this.form.activityItems);
                    this._dataArr(data.selectedActivities, this.form.activities);
                    this._dataArr(data.selectedActivities2, this.form.activities2);
                } else {
                    this.errorFun(data.msg);
                }
            })
        },
        _dataPush(firstData, lastData) {
            for (var key in firstData) {
                lastData.push({ label: key, value: firstData[key] })
            }
        },
        _dataArr(firstData, lastData) {
            for (var key in firstData) {
                lastData.push(firstData[key])
            }

        },
        //根据选项,确定日期范围,7,15,30,custom
        getDateRangeByDateType(dateType) {
            const end = new Date();
            const start = new Date();
            switch (dateType) {
                case 7:
                    this.form.dstart = formatGMTDate(new Date(start.getTime() - 3600 * 1000 * 24 * 7), true);
                    this.form.dend = formatGMTDate(new Date(end), true);
                case 15:
                    this.form.dstart = formatGMTDate(new Date(start.getTime() - 3600 * 1000 * 24 * 15), true);
                    this.form.dend = formatGMTDate(new Date(end), true);
                case 30:
                    this.form.dstart = formatGMTDate(new Date(start.getTime() - 3600 * 1000 * 24 * 30), true);
                    this.form.dend = formatGMTDate(new Date(end), true);
                default:
            }
        },
        //占百分比字段显示
        formatData() {
            //整体数据
            var allData = this.activityAnalysisTableDataAll;
            for (var i = 0; i < allData.length; i++) {
                for (var j in allData[i]) {
                    if (j === 'userJoinRate') {
                        allData[i][j] = toPercent(allData[i][j]);
                    }
                }
            }
            this.activityAnalysisTableDataAll = allData;
        },
        /*设置初始值*/
        _init() {
            /**init charts */
            var linecharthtmlElements = ["joinRateTaskCharts", "joinRateSubTaskCharts"];
            var barcharthtmlElements = ["joinRateAvgTaskCharts", "joinRateAvgSubTaskCharts"];

            for (var x = 0; x < linecharthtmlElements.length; x++) {
                this.chartsWidth(linecharthtmlElements[x]);
                this[linecharthtmlElements[x]] = echarts.init(document.getElementById(linecharthtmlElements[x]));
                this[linecharthtmlElements[x]].setOption(this.lineChartSetting);
            }
            for (var y = 0; y < barcharthtmlElements.length; y++) {
                this.chartsWidth(barcharthtmlElements[y]);
                this[barcharthtmlElements[y]] = echarts.init(document.getElementById(barcharthtmlElements[y]));
                this[barcharthtmlElements[y]].setOption(this.barChartsSetting);
            }
            window.addEventListener('resize', function() {
                /*修改表格的宽度*/
                this.tableWidth = document.body.clientWidth - 240 + "px";
                this.contentWidth = document.body.clientWidth - 220 + "px";

                for (var i in linecharthtmlElements) {
                    this.chartsWidth(linecharthtmlElements[i]);
                }
                for (var i in barcharthtmlElements) {
                    this.chartsWidth(barcharthtmlElements[i]);
                }
                var resizeArr = ["joinRateTaskCharts", "joinRateSubTaskCharts", "joinRateAvgTaskCharts", "joinRateAvgSubTaskCharts"];
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }

            }.bind(this))
        },
        chartsWidth(el) {
            if (document.getElementById(el) !== null && el.indexOf('payType') != -1) {
                document.getElementById(el).style.width = (window.innerWidth - 290) / 3 + "px";
            } else if (document.getElementById(el) !== null) {
                document.getElementById(el).style.width = window.innerWidth - 290 + "px";
            }
        },
        //update platform/channel/server
        updatePlatform(val) {
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "updatePlatform",
                    ps: `platform=${val}`
                }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data.res) == 0) {
                    this.form.channelItems = [];
                    this.form.serverItmes = [];
                    this._dataPush(data.channelItmes, this.form.channelItems);
                    this._dataPush(data.serverItmes, this.form.serverItmes);
                } else {
                    // this.errorFun(data.msg);
                }
            });
        },
        updateChannel(val) {
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "updateChannel",
                    ps: `channel=${val}`
                }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data.res) == 0) {
                    this.form.platformItmes = [];
                    this.form.serverItmes = [];
                    this._dataPush(data.serverItmes, this.form.serverItmes);
                    this._dataPush(data.platformItmes, this.form.platformItmes);
                } else {
                    // this.errorFun(data.msg);
                }
            });
        },
        updateServer(val) {
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "updateServer",
                    ps: `server=${val}`
                }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data.res) == 0) {
                    this.form.platformItmes = [];
                    this.form.channelItmes = [];
                    this._dataPush(data.channelItmes, this.form.channelItems);
                    this._dataPush(data.platformItmes, this.form.platformItmes);
                } else {
                    // this.errorFun(data.msg);
                }
            });
        }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this._init();

        this.date = [new Date(new Date().getTime() - 8 * 86400000), new Date(new Date().getTime() - 86400000)];
        this.form.dstart = formatGMTDate(new Date(new Date().getTime() - 8 * 86400000), true);
        this.form.dend = formatGMTDate(new Date(new Date().getTime() - 86400000), true);
        this.getData();
    }
}